#!/usr/bin/env python3
"""
检测区域可视化工具
显示主要颜色检测的区域大小和位置
"""

import pyautogui
import tkinter as tk
from tkinter import ttk
import time
from utils.dominant_color_detector import DominantColorDetector

class DetectionAreaVisualizer:
    """检测区域可视化器"""
    
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("颜色检测区域可视化")
        self.root.geometry("600x500")
        self.root.attributes('-topmost', True)  # 保持在最前面
        
        # 检测器
        self.detector = None
        self.overlay_window = None
        
        self.setup_ui()
        
    def setup_ui(self):
        """设置UI界面"""
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 标题
        title_label = ttk.Label(main_frame, text="颜色检测区域可视化", font=("Arial", 16, "bold"))
        title_label.grid(row=0, column=0, columnspan=2, pady=(0, 20))
        
        # 参数设置区域
        params_frame = ttk.LabelFrame(main_frame, text="检测参数", padding="10")
        params_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 区域大小设置
        ttk.Label(params_frame, text="检测区域大小:").grid(row=0, column=0, sticky=tk.W)
        self.region_size_var = tk.StringVar(value="200")
        region_size_combo = ttk.Combobox(params_frame, textvariable=self.region_size_var, 
                                       values=["50", "100", "150", "200", "250", "300"], width=10)
        region_size_combo.grid(row=0, column=1, padx=(5, 0))
        ttk.Label(params_frame, text="像素").grid(row=0, column=2, padx=(5, 0))
        
        # 聚类数量设置
        ttk.Label(params_frame, text="K-Means聚类数:").grid(row=1, column=0, sticky=tk.W, pady=(5, 0))
        self.clusters_var = tk.StringVar(value="3")
        clusters_combo = ttk.Combobox(params_frame, textvariable=self.clusters_var,
                                    values=["2", "3", "4", "5"], width=10)
        clusters_combo.grid(row=1, column=1, padx=(5, 0), pady=(5, 0))
        
        # 信息显示区域
        info_frame = ttk.LabelFrame(main_frame, text="屏幕信息", padding="10")
        info_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 屏幕尺寸
        screen_width, screen_height = pyautogui.size()
        screen_info = f"屏幕尺寸: {screen_width} x {screen_height} 像素"
        ttk.Label(info_frame, text=screen_info).grid(row=0, column=0, sticky=tk.W)
        
        # 屏幕中心
        center_x, center_y = screen_width // 2, screen_height // 2
        center_info = f"屏幕中心: ({center_x}, {center_y})"
        ttk.Label(info_frame, text=center_info).grid(row=1, column=0, sticky=tk.W)
        
        # 检测区域信息
        self.area_info_label = ttk.Label(info_frame, text="")
        self.area_info_label.grid(row=2, column=0, sticky=tk.W)
        
        # 当前颜色信息
        self.color_info_label = ttk.Label(info_frame, text="")
        self.color_info_label.grid(row=3, column=0, sticky=tk.W)
        
        # 按钮区域
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=3, column=0, columnspan=2, pady=(10, 0))
        
        # 显示检测区域按钮
        self.show_area_btn = ttk.Button(button_frame, text="显示检测区域", command=self.show_detection_area)
        self.show_area_btn.grid(row=0, column=0, padx=(0, 10))
        
        # 隐藏检测区域按钮
        self.hide_area_btn = ttk.Button(button_frame, text="隐藏检测区域", command=self.hide_detection_area)
        self.hide_area_btn.grid(row=0, column=1, padx=(0, 10))
        
        # 实时检测按钮
        self.start_detection_btn = ttk.Button(button_frame, text="开始实时检测", command=self.start_real_time_detection)
        self.start_detection_btn.grid(row=0, column=2, padx=(0, 10))
        
        # 停止检测按钮
        self.stop_detection_btn = ttk.Button(button_frame, text="停止检测", command=self.stop_real_time_detection)
        self.stop_detection_btn.grid(row=0, column=3)
        
        # 实时检测状态
        self.detecting = False
        
        # 更新区域信息
        self.update_area_info()
        
        # 绑定参数变化事件
        region_size_combo.bind('<<ComboboxSelected>>', lambda e: self.update_area_info())
        clusters_combo.bind('<<ComboboxSelected>>', lambda e: self.update_area_info())
    
    def update_area_info(self):
        """更新区域信息显示"""
        try:
            region_size = int(self.region_size_var.get())
            screen_width, screen_height = pyautogui.size()
            center_x, center_y = screen_width // 2, screen_height // 2
            
            # 计算检测区域边界
            half_size = region_size // 2
            left = center_x - half_size
            top = center_y - half_size
            right = center_x + half_size
            bottom = center_y + half_size
            
            area_info = f"检测区域: ({left}, {top}) 到 ({right}, {bottom}) - {region_size}x{region_size} 像素"
            self.area_info_label.config(text=area_info)
            
            # 计算像素数量
            pixel_count = region_size * region_size
            pixel_info = f"总像素数: {pixel_count:,} 个像素"
            
            # 更新显示
            if hasattr(self, 'pixel_info_label'):
                self.pixel_info_label.config(text=pixel_info)
            else:
                self.pixel_info_label = ttk.Label(self.area_info_label.master, text=pixel_info)
                self.pixel_info_label.grid(row=4, column=0, sticky=tk.W)
                
        except ValueError:
            self.area_info_label.config(text="无效的区域大小")
    
    def show_detection_area(self):
        """显示检测区域覆盖层"""
        try:
            region_size = int(self.region_size_var.get())
            screen_width, screen_height = pyautogui.size()
            center_x, center_y = screen_width // 2, screen_height // 2
            
            # 计算检测区域边界
            half_size = region_size // 2
            left = center_x - half_size
            top = center_y - half_size
            
            # 创建覆盖层窗口
            if self.overlay_window:
                self.overlay_window.destroy()
            
            self.overlay_window = tk.Toplevel()
            self.overlay_window.title("检测区域")
            self.overlay_window.geometry(f"{region_size}x{region_size}+{left}+{top}")
            self.overlay_window.attributes('-topmost', True)
            self.overlay_window.attributes('-alpha', 0.3)  # 半透明
            self.overlay_window.configure(bg='red')
            
            # 添加标签
            label = tk.Label(self.overlay_window, text=f"检测区域\n{region_size}x{region_size}", 
                           bg='red', fg='white', font=("Arial", 12, "bold"))
            label.pack(expand=True)
            
            # 5秒后自动隐藏
            self.root.after(5000, self.hide_detection_area)
            
        except ValueError:
            tk.messagebox.showerror("错误", "无效的区域大小")
    
    def hide_detection_area(self):
        """隐藏检测区域覆盖层"""
        if self.overlay_window:
            self.overlay_window.destroy()
            self.overlay_window = None
    
    def start_real_time_detection(self):
        """开始实时检测"""
        try:
            region_size = int(self.region_size_var.get())
            k_clusters = int(self.clusters_var.get())
            
            # 创建检测器
            self.detector = DominantColorDetector(
                region_size=region_size,
                k_clusters=k_clusters,
                cache_duration=0.01
            )
            
            self.detecting = True
            self.start_detection_btn.config(state='disabled')
            self.stop_detection_btn.config(state='normal')
            
            # 开始检测循环
            self.detection_loop()
            
        except ValueError:
            tk.messagebox.showerror("错误", "无效的参数")
    
    def stop_real_time_detection(self):
        """停止实时检测"""
        self.detecting = False
        self.start_detection_btn.config(state='normal')
        self.stop_detection_btn.config(state='disabled')
        self.color_info_label.config(text="检测已停止")
    
    def detection_loop(self):
        """检测循环"""
        if not self.detecting:
            return
        
        try:
            # 清除缓存确保实时检测
            if self.detector:
                self.detector.clear_cache()
                
                # 获取主要颜色
                dominant_color, confidence, detection_info = self.detector.get_dominant_color_at_center(use_cache=False)
                
                if dominant_color:
                    # 显示颜色信息
                    color_text = f"主要颜色: RGB{dominant_color} (置信度: {confidence:.3f})"
                    self.color_info_label.config(text=color_text)
                    
                    # 显示所有检测到的颜色
                    all_colors = detection_info.get('all_colors', [])
                    weights = detection_info.get('weights', [])
                    
                    if len(all_colors) > 1:
                        detail_text = "所有颜色: "
                        for i, (color, weight) in enumerate(zip(all_colors[:3], weights[:3])):
                            detail_text += f"RGB{color}({weight:.2f}) "
                        
                        if hasattr(self, 'detail_info_label'):
                            self.detail_info_label.config(text=detail_text)
                        else:
                            self.detail_info_label = ttk.Label(self.color_info_label.master, text=detail_text)
                            self.detail_info_label.grid(row=5, column=0, sticky=tk.W)
                else:
                    self.color_info_label.config(text="检测失败")
        
        except Exception as e:
            self.color_info_label.config(text=f"检测错误: {e}")
        
        # 继续检测循环
        if self.detecting:
            self.root.after(100, self.detection_loop)  # 10Hz检测频率
    
    def run(self):
        """运行可视化工具"""
        self.root.mainloop()

def main():
    """主函数"""
    print("🔍 颜色检测区域可视化工具")
    print("=" * 50)
    
    # 显示当前配置信息
    screen_width, screen_height = pyautogui.size()
    center_x, center_y = screen_width // 2, screen_height // 2
    
    print(f"屏幕信息:")
    print(f"  尺寸: {screen_width} x {screen_height} 像素")
    print(f"  中心点: ({center_x}, {center_y})")
    
    print(f"\n默认检测区域配置:")
    print(f"  区域大小: 200x200 像素")
    print(f"  检测范围: ({center_x-100}, {center_y-100}) 到 ({center_x+100}, {center_y+100})")
    print(f"  总像素数: 40,000 个像素")
    print(f"  K-Means聚类: 3 个")
    
    print(f"\n不同配置的检测区域:")
    sizes = [50, 100, 150, 200, 250, 300]
    for size in sizes:
        half = size // 2
        pixels = size * size
        print(f"  {size}x{size}: ({center_x-half}, {center_y-half}) 到 ({center_x+half}, {center_y+half}) - {pixels:,} 像素")
    
    print(f"\n启动可视化工具...")
    
    # 启动可视化工具
    visualizer = DetectionAreaVisualizer()
    visualizer.run()

if __name__ == "__main__":
    main()
